package com.zyf.service;

import cn.hutool.core.io.FileUtil;
import com.zyf.service.audio.HandleAudioService;
import com.zyf.service.video.HandleVideoService;
import com.zyf.service.video.VedioUtils;
import com.zyf.tts.TTS;
import com.zyf.tts.TTSVoice;
import com.zyf.tts.bean.Voice;
import com.zyf.utils.FFmpegUtils;
import com.zyf.utils.StringUtil;
import it.sauronsoftware.jave.AudioAttributes;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncodingAttributes;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FrameRecorder;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 名人名言短视频制作处理类
 */
public class HandleMYFLVideoService {

    private static final double RATE = 0.002;

    /**
     * 批量一键生成图签视频
     */
    public void batchMakeShortVideos(String folderPath) throws Exception {
        //先批量生成配音文件
        List<File> txtList = FileUtil.loopFiles(folderPath, backfile -> backfile.isFile() && backfile.getName().endsWith(".txt"));
        for (File file : txtList) {
            String filepath = handleSingleTTS(file.getAbsolutePath());
        }
        //筛选文件夹
        File[] handDataList = new File(folderPath).listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return pathname.isDirectory();
            }
        });
        //遍历文件夹批量处理
        List<String> tips = new ArrayList<>();
        for (File file : handDataList) {
            try {
                String fielfolderPath = file.getAbsolutePath();
                List<File> backList = FileUtil.loopFiles(fielfolderPath, backfile -> backfile.isFile() && (backfile.getName().endsWith(".mp3") || backfile.getName().endsWith(".wav")) && backfile.getName().contains("back"));
                List<File> srcList = FileUtil.loopFiles(fielfolderPath, srcfile -> srcfile.isFile() && (srcfile.getName().endsWith(".mp3") || srcfile.getName().endsWith(".wav")) && !srcfile.getName().contains("back"));
                List<File> mp4BackList = FileUtil.loopFiles(fielfolderPath, mp4file -> mp4file.isFile() && (mp4file.getName().endsWith(".mp4")) && mp4file.getName().contains("back"));
                List<File> srctxtList = FileUtil.loopFiles(fielfolderPath, txtfile -> txtfile.isFile() && txtfile.getName().endsWith(".txt"));
                makeVideoByTag(srcList.get(0).getAbsolutePath(), backList.get(0).getAbsolutePath(), mp4BackList.get(0).getAbsolutePath(), srctxtList.get(0).getAbsolutePath());
            } catch (Exception e) {
                tips.add(e.toString());
            }
        }
    }

    public String handleSingleTTS(String txtFile) throws IOException {
        File file = new File(txtFile);
        String finalPath = txtFile.replace(".txt", ".mp3");
        String filename = file.getName().substring(0, file.getName().indexOf("."));
        //读取源文件
        String srcContent = getSrcTxtByLine(txtFile);
        Voice voice = TTSVoice.provides().stream().filter(v -> v.getShortName().equals("zh-CN-YunjianNeural")).collect(Collectors.toList()).get(0);
        String fileName = new TTS(voice, srcContent).findHeadHook().fileName(filename).formatMp3().storage(file.getParent())
//                .formatOpus() // or opus
//                .voicePitch()
//                .voiceRate()
                .voiceVolume("500")
                .trans();
        String vttPath = file.getParent() + File.separator + fileName + ".mp3.vtt";
        File vttfile = new File(vttPath);
        if (vttfile.exists()) {
            vttfile.delete();
        }
        return finalPath;
    }

    public String getSrcTxtByLine(String filepath) throws FileNotFoundException {
        String[] punctuation = {"。", "，", "、", "；", "：", "？", "！", "•", ".", "—"};
        List<String> punctuations = Arrays.asList(punctuation);
        StringBuffer buffer = new StringBuffer();
        InputStream inputstream = new FileInputStream(new File(filepath));
        BufferedReader reader = null;
        String temp = "";
        try {
            int index = 0;
            reader = new BufferedReader(new InputStreamReader(inputstream));
            while ((temp = reader.readLine()) != null) {
                if (index > 1) {
                    buffer.append(temp.trim());
                } else {
                    buffer.append(temp.trim());
                    buffer.append("\n");
                }
                index++;
            }
        } catch (IOException e) {
            if (reader != null)
                try {
                    reader.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return buffer.toString();
    }

    /**
     * 一键合成文字书签视频
     *
     * @return
     * @throws Exception
     */
    public boolean makeVideoByTag(String audiopath, String backpath, String mp4Path, String srctxtPath) throws Exception {
        try {
            //合成音频
            Map<String, String> resMap = mergeAudioAndBackBySrtAndTag(audiopath, backpath);
            //合成视频字幕
            String message = makeSingleVideo(mp4Path, resMap.get("audio"), resMap.get("srt"));//合成视频
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return true;
    }

    public boolean makeVideo(String srctxtPath) throws Exception {
        try {
            List<File> mp4List = FileUtil.loopFiles(new File(srctxtPath).getParent(), mp4file -> mp4file.isFile() && (mp4file.getName().endsWith(".mp4")));
            String filepath = handleSingleTTS(srctxtPath);
            //合成音频
            Map<String, String> resMap = generateSrt(filepath);
            //合成视频字幕
            String message = makeSingleVideo(mp4List.get(0).getAbsolutePath(), resMap.get("audio"), resMap.get("srt"));//合成视频
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return true;
    }

    /**
     * 制作单个的长视频
     */
    public String makeSingleVideo(String backMp4Path, String finalAudio, String finalSrt) throws Exception {
        //抓取内容视频的宽高
        FFmpegFrameGrabber grabberVideo = null;
        FFmpegFrameGrabber grabberAudio = null;
        long durationAudio = 0;
        try {
            //抓取视频帧
            grabberVideo = new FFmpegFrameGrabber(backMp4Path);
            grabberAudio = new FFmpegFrameGrabber(finalAudio);
            grabberVideo.start();
            grabberAudio.start();
            //获取时长,以短的文件为主进行截取
            long durationVideo = grabberVideo.getFormatContext().duration() / 1000000;
            durationAudio = grabberAudio.getFormatContext().duration() / 1000000;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (grabberVideo != null) {
                grabberVideo.stop();
                grabberVideo.release();
            }
        }
        //合成音频
        System.out.println("开始合成视频和音频-----");
        String mp4path = mergeVediosAndAudio(backMp4Path, finalAudio);
        System.out.println("-----合成视频和音频结束");
        //合并视频和字幕
        new HandleVideoService().mergeVediosAndSrtByDoubleFile(mp4path, finalSrt);

        return "操作成功";
    }

    /**
     * 读取源文件
     */
    private List<String> getSrcTxt(String filepath) throws FileNotFoundException {
        List<String> srcTxtlist = new ArrayList<>();
        InputStream inputstream = new FileInputStream(new File(filepath));
        BufferedReader reader = null;
        String temp = "";
        try {
            reader = new BufferedReader(new InputStreamReader(inputstream));
            while ((temp = reader.readLine()) != null) {
                if (temp.length() > 0) {
                    srcTxtlist.add(temp);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return srcTxtlist;
    }

    /**
     * 合并视频和音频,以长度短的为基准
     * <p>
     * ffmpeg -i input_video.mp4 -i input_audio.mp3 -c:v copy -c:a aac -strict experimental -b:a 192k output_video.mp4
     *
     * @throws Exception
     */
    public String mergeVediosAndAudio(String videoPath, String audioPath) throws Exception {
        String videoFinalfile = videoPath.replace(".mp4", "_final.mp4");
        File file = new File(videoFinalfile);
        if (file.exists()) {
            file.delete();
        }
        FFmpegFrameGrabber grabberVideo = null;
        FFmpegFrameGrabber grabberAudio = null;
        try {
            //抓取视频帧
            grabberVideo = new FFmpegFrameGrabber(videoPath);
            //抓取音频帧
            grabberAudio = new FFmpegFrameGrabber(audioPath);
            grabberVideo.start();
            grabberAudio.start();
            //获取时长,以短的文件为主进行截取
            long durationVideo = grabberVideo.getFormatContext().duration() / 1000000;
            long durationAudio = grabberAudio.getFormatContext().duration() / 1000000;
            if (durationVideo != durationAudio) {
                if (durationVideo > durationAudio) {//音频短则以音频长度为主
                    //截取视频
                    videoPath = new VedioUtils().cutVideoByDurationAndStartZ(videoPath, durationAudio);
                } else {
                    //截取音频
                    audioPath = new HandleAudioService().cutAudioByStart(audioPath, durationVideo, "wav");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (grabberVideo != null) {
                grabberVideo.stop();
                grabberVideo.release();
            }
            if (grabberAudio != null) {
                grabberAudio.stop();
                grabberAudio.release();
            }
        }
        try {
            List<String> commands = new ArrayList<>();
            commands.add("ffmpeg");
            commands.add("-i");
            commands.add(videoPath);
            commands.add("-i");
            commands.add(audioPath);
            commands.add("-c:v");
            commands.add("copy");
            commands.add("-c:a");
            commands.add("aac");
            commands.add("-strict");
            commands.add("experimental");
            commands.add("-b:a");
            commands.add("192k");
            commands.add(videoFinalfile);

            String res = FFmpegUtils.execFFmpegCommand(commands);
            System.out.println(res);
        } catch (Exception e) {
            throw new RuntimeException("ffmpeg执行异常" + e.getMessage());
        }
        return videoFinalfile;
    }

    /**
     * 延长视频到指定长度
     *
     * @param videopath
     * @param duation
     */
    public String extendVideo(String videopath, String duation) throws Exception {
        //获取视频原始时长
        FFmpegFrameGrabber grabberVideo = null;
        int durationVideo = 0;
        int total = Integer.valueOf(duation);
        try {
            //抓取视频帧
            grabberVideo = new FFmpegFrameGrabber(videopath);
            grabberVideo.start();
            //获取时长,以短的文件为主进行截取
            String resdura = grabberVideo.getFormatContext().duration() / 1000000 + "";

            durationVideo = Integer.valueOf(resdura);

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            grabberVideo.release();
            grabberVideo.stop();
        }
        int circle = total / durationVideo + 1;
        String finalMp4Path = videopath.replace(".mp4", "_final.mp4");

        List<String> commands = new ArrayList<>();
        commands.add("ffmpeg");
        commands.add("-stream_loop");
        commands.add(circle + "");
        commands.add("-i");
        commands.add(videopath);
        commands.add("-c");
        commands.add("copy");
        commands.add(finalMp4Path);

        String res = FFmpegUtils.execFFmpegCommand(commands);
        System.out.println(res);
        //视频生成完毕后进行截取
        //将5分钟转化为时分秒
        int hours = total / 3600;
        int minus = (total % 3600) / 60;
        int second = total - hours * 3600 - minus * 60;
        StringBuffer buffer = new StringBuffer();
        if (hours < 10) {
            buffer.append("0" + hours);
        } else {
            buffer.append("" + hours);
        }
        buffer.append(":");
        if (minus < 10) {
            buffer.append("0" + minus);
        } else {
            buffer.append("" + minus);
        }
        buffer.append(":");
        if (second < 10) {
            buffer.append("0" + second);
        } else {
            buffer.append("" + second);
        }

        String finalPath = new VedioUtils().cutVideoByFFmpeg(finalMp4Path, "00:00:00", buffer.toString());
        File oldFile = new File(finalMp4Path);
        if (oldFile.exists()) {
            oldFile.delete();
        }
        return finalPath;
    }

    /**
     * 创建mp4指定帧率
     *
     * @param mp4SavePath
     * @param width
     * @param height
     * @throws FrameRecorder.Exception
     */
    public static void createMp4ByFFmpegAndFrameRate(String mp4SavePath, String imgFile, int width, int height, double frameRate, int duration) throws Exception {
        File mp4File = new File(mp4SavePath);
        if (mp4File.exists()) {
            mp4File.delete();
        }

        List<String> commands = new ArrayList<>();
        commands.add("ffmpeg");
        commands.add("-loop");
        commands.add("1");
        commands.add("-framerate");
        commands.add(frameRate + "");
        commands.add("-i");
        commands.add(imgFile);
        commands.add("-t");
        commands.add(duration + "");
        commands.add("-c:v");
        commands.add("libx264");
        commands.add("-b:v");
        commands.add("2000k");
        commands.add("-crf");
        commands.add("18");
        commands.add("-pix_fmt");
        commands.add("yuv420p");
        commands.add("-s");
        commands.add(width + "X" + height);
        commands.add(mp4SavePath);

        String res = FFmpegUtils.execFFmpegCommand(commands);
        System.out.println(res);
    }

    /**
     * 音频添加背景乐并生成字幕文件(音量默认0.1)
     */
    public Map<String, String> mergeAudioAndBackBySrtAndTag(String srcaudiopath, String backpath) throws Exception {
        Map<String, String> resMap = new HashMap<>();
        File audioFile = new File(srcaudiopath);
        if (!audioFile.exists()) {
            throw new RuntimeException("源音频不存在");
        }
        File backFile = new File(backpath);
        if (!backFile.exists()) {
            throw new RuntimeException("背景音频不存在");
        }
        FFmpegFrameGrabber grabber = null;
        long durationInSec = 0l;
        try {
            grabber = new FFmpegFrameGrabber(srcaudiopath);
            grabber.start();
            durationInSec = grabber.getFormatContext().duration() / 1000000;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            grabber.release();
            grabber.close();
        }
        //统一转为wav无损模式
        if (audioFile.getName().endsWith(".mp3")) {
            srcaudiopath = converAudio(srcaudiopath);
        }
        try {
            //源音频生成字幕文件
            String finalsrt = audioToSrtBySilence(srcaudiopath);
            resMap.put("srt", finalsrt);
            //添加前缀
            String prefixaudio = new VedioUtils().mergePrefix2Audio(srcaudiopath);
            //合成音频根据ffmpeg
            String finalaudio = mixSingleAudioByFFmpeg(prefixaudio, backpath);
            //调大音量5倍
            String finaleVolumeAudio = controAudioVolume(finalaudio, 5f);
            resMap.put("audio", finaleVolumeAudio);
            List<File> srctxtList = FileUtil.loopFiles(audioFile.getParent(), file -> file.isFile() && file.getName().endsWith(".txt"));
            if (srctxtList == null || srctxtList.size() <= 0) {
                throw new RuntimeException("字幕源文件不存在");
            }
            File prefixaudiofile = new File(prefixaudio);
            if (prefixaudiofile.exists()) {
                prefixaudiofile.delete();
            }
            File srcaudiopathfile = new File(srcaudiopath.replace(".wav", ".mp3"));
            if (srcaudiopathfile.exists()) {
                srcaudiopathfile.delete();
            }
            File finalaudiofile = new File(finalaudio);
            if (finalaudiofile.exists()) {
                finalaudiofile.delete();
            }
            File backpathfile = new File(backpath.replace(".wav", ".mp3"));
            if (backpathfile.exists()) {
                backpathfile.delete();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            grabber.release();
            grabber.close();
        }
        return resMap;
    }

    /**
     * 音频添加背景乐并生成字幕文件(音量默认0.1)
     */
    public Map<String, String> generateSrt(String srcaudiopath) throws Exception {
        Map<String, String> resMap = new HashMap<>();
        File audioFile = new File(srcaudiopath);
        if (!audioFile.exists()) {
            throw new RuntimeException("源音频不存在");
        }
        //统一转为wav无损模式
        if (audioFile.getName().endsWith(".mp3")) {
            srcaudiopath = converAudio(srcaudiopath);
        }
        try {
            //源音频生成字幕文件
            String finalsrt = audioToSrtBySilence(srcaudiopath);
            resMap.put("srt", finalsrt);
            //调大音量5倍
            String finaleVolumeAudio = controAudioVolume(srcaudiopath, 5f);
            resMap.put("audio", finaleVolumeAudio);
            List<File> srctxtList = FileUtil.loopFiles(audioFile.getParent(), file -> file.isFile() && file.getName().endsWith(".txt"));
            if (srctxtList == null || srctxtList.size() <= 0) {
                throw new RuntimeException("字幕源文件不存在");
            }

            File srcaudiopathfile = new File(srcaudiopath.replace(".wav", ".mp3"));
            if (srcaudiopathfile.exists()) {
                srcaudiopathfile.delete();
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return resMap;
    }

    /**
     * 调整音量大小
     * ffmpeg -i input.mp3 -af "volume=0.1" output.mp3
     * <p>
     * ffmpeg -i input.mp3 -af "volume=10dB" output.mp3
     */
    public String controAudioVolume(String audiopath, float volume) throws Exception {
        File audioFile = new File(audiopath);
        String fileName = audioFile.getName();
        if (!audioFile.exists()) {
            throw new RuntimeException("文件不存在");
        }
        String outpath = audiopath.replace(".", "_final_hebing.");
        //生成str字幕文件
        List<String> commands = new ArrayList<>();
        commands.add("ffmpeg");
        commands.add("-i");
        commands.add(audiopath);
        commands.add("-af");
        commands.add("\"volume=" + volume + "\"");
        commands.add(outpath);

        String result = FFmpegUtils.execFFmpegCommand(commands);
        System.out.println(result);
        return outpath;
    }

    /**
     * 指定音频添加指定背景乐,统一用wav无损模式处理音频
     * ffmpeg -i main_audio.mp3 -stream_loop -1 -i background_music.mp3 -filter_complex "[0:a][1:a]amix=inputs=2:duration=first" -c:a libmp3lame -qscale:a 2 output.mp3
     * ffmpeg -i main_audio.mp3 -i background_music.mp3 -filter_complex "[1:a]volume=0.5[a];[0:a][a]amix=inputs=2:duration=first" -c:a libmp3lame -qscale:a 2 output.mp3
     *
     * @throws IOException
     */
    public String mixSingleAudioByFFmpeg(String srcpath, String backpath) throws Exception {
        File audioFile = new File(srcpath);
        if (!audioFile.exists()) {
            throw new RuntimeException("主音频文件不存在");
        }
        File backFile = new File(backpath);
        if (!backFile.exists()) {
            throw new RuntimeException("背景音频文件不存在");
        }
        //格式统一转换为wav
        if (audioFile.getName().endsWith(".mp3")) {
            srcpath = converAudio(srcpath);
        }
        //格式统一转换为wav
        if (backFile.getName().endsWith(".mp3")) {
            backpath = converAudio(backpath);
        }
        String outpath = srcpath.replace(".", "_merge.");
        File outFile = new File(outpath);
        if (outFile.exists()) {
            outFile.delete();
        }
//        //获取原音频音量
//        float srcVolume= getAudioVolume(srcpath);
//        //获取相适应的背景音频音量
//        float lastVolume=srcVolume/VOLUMERATE;
//        //获取调整比率
//        float backVolume= getAudioVolume(backpath);
//        //rate
//        float rate=backVolume/lastVolume;
//        String lastRate=String.format("%.2f", rate);
//        System.out.println(lastRate);

        //合并音频
        List<String> commands = new ArrayList<>();
        commands.add("ffmpeg");
        commands.add("-i");
        commands.add(srcpath);
        commands.add("-stream_loop");
        commands.add("-1");
        commands.add("-i");
        commands.add(backpath);
        commands.add("-filter_complex");
        commands.add("\"[1:a]volume=0.25[a];[0:a][a]amix=inputs=2:duration=first\"");
        commands.add("-c:a");
//        commands.add("libmp3lame");
        commands.add("pcm_s16le");//wav格式
        commands.add("-qscale:a");
        commands.add("2");
        commands.add(outpath);

        String result = FFmpegUtils.execFFmpegCommand(commands);
        System.out.println(result);

        return outpath;
    }

    /**
     * 音频转字幕文件:通过静音位置进行处理
     * ffmpeg -i input.wav -af silencedetect=-60dB:d=0.5 -f null -
     */
    public String audioToSrtBySilence(String audioFilePath) throws Exception {
        File audioFile = new File(audioFilePath);
        String fileName = audioFile.getName();
        if (!audioFile.exists()) {
            throw new RuntimeException("音频不存在");
        }
        //获取txt文件
        List<File> txtList = FileUtil.loopFiles(audioFile.getParent(), file -> file.isFile() && file.getName().endsWith(".txt"));
        if (txtList == null || txtList.isEmpty()) {
            throw new RuntimeException("文本不存在");
        }
        //生成str字幕文件
        List<String> commands = new ArrayList<>();
        commands.add("ffmpeg");
        commands.add("-i");
        commands.add(audioFilePath);
        commands.add("-af");
        commands.add("silencedetect=-60dB:d=0.5");//medium  small
        commands.add("-f");
        commands.add("null");
        commands.add("-");

        String result = FFmpegUtils.execFFmpegCommand(commands);
        System.out.println(result);
        //解析返回参数并生成参数
        Map<Integer, String> silenceMap = new HashMap<>();
        String[] endstrs = result.split("silence_start");
        int index = 0;
        for (String str : endstrs) {
            if (str.contains("silence_end:")) {
                String endtiem = str.substring(str.indexOf("silence_end:") + 12, str.indexOf("|")).trim();
                endtiem = Float.valueOf(endtiem) * 1000 + "";
                if (endtiem.contains(".")) {
                    endtiem = endtiem.substring(0, endtiem.indexOf("."));
                }
                silenceMap.put(index, endtiem);
                System.out.println("结束时间：" + (Integer.valueOf(endtiem) / 1000));
                index++;
            }
        }
        System.out.println("次数：" + index);
        String resPath = new HandleSpeechService().createSrtBySilence(txtList.get(0).getAbsolutePath(), silenceMap);
        return resPath;
    }

    /**
     * 音频转换
     */
    public String converAudio(String audioFilePath) {
        File inaudioFile = new File(audioFilePath);
        if (!inaudioFile.exists()) {
            throw new RuntimeException("音频文件不存在");
        }
        String filename = inaudioFile.getName();
        if (filename.contains("mp3")) {//默认转wav
            String outFilePath = audioFilePath.replace(".mp3", ".wav");
            File outFile = new File(outFilePath);
            try {
                AudioAttributes audioAttributes = new AudioAttributes();
                audioAttributes.setCodec("pcm_s16le");
                audioAttributes.setBitRate(new Integer(128000));
                audioAttributes.setChannels(new Integer(2));
                audioAttributes.setSamplingRate(new Integer(44100));

                EncodingAttributes encodingAttributes = new EncodingAttributes();
                encodingAttributes.setFormat("wav");
                encodingAttributes.setAudioAttributes(audioAttributes);

                Encoder encoder = new Encoder();
                encoder.encode(inaudioFile, outFile, encodingAttributes);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return outFilePath;
        }
        if (filename.contains("wav")) {//默认转mp3
            String mp3FilePath = audioFilePath.replace(".wav", ".mp3");
            File outFile = new File(mp3FilePath);
            try {
                AudioAttributes audioAttributes = new AudioAttributes();
                audioAttributes.setCodec("libmp3lame");
                audioAttributes.setBitRate(new Integer(128080));
                audioAttributes.setChannels(new Integer(2));
                audioAttributes.setSamplingRate(new Integer(44100));

                EncodingAttributes encodingAttributes = new EncodingAttributes();
                encodingAttributes.setFormat("mp3");
                encodingAttributes.setAudioAttributes(audioAttributes);

                Encoder encoder = new Encoder();
                encoder.encode(inaudioFile, outFile, encodingAttributes);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return mp3FilePath;
        }
        return "";
    }


    /**
     * 读取源文件
     */
    private List<String> checkSrcTxtByLine(String filepath) throws FileNotFoundException {
        List<String> messages = new ArrayList<>();
        InputStream inputstream = new FileInputStream(new File(filepath));
        BufferedReader reader = null;
        String temp = "";
        List<String> newSrtList = new ArrayList<>();
        try {
            reader = new BufferedReader(new InputStreamReader(inputstream));
            while ((temp = reader.readLine()) != null) {

            }
        } catch (IOException e) {
            if (reader != null)
                try {
                    reader.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return messages;
    }

    /**
     * 处理诗词文件,移动背景音乐,视频
     */
    public void handleTXT(String txtFile, String videoFolder) throws Exception {
        File back = new File(txtFile);
        List<File> sourceFile = FileUtil.loopFiles(back.getParent(), file -> file.isFile() && (file.getName().endsWith(".mp3") || file.getName().endsWith(".wav")));
        List<File> mp4list = FileUtil.loopFiles(videoFolder, MP4file -> MP4file.isFile() && (MP4file.getName().endsWith(".mp4")));
        if (sourceFile == null || sourceFile.size() <= 0) {
            throw new RuntimeException("背景音乐不存在");
        }
        //创建一级文件夹
        String firstLevelFolder = txtFile.substring(0, txtFile.indexOf("."));
        File firstLevelFolderFile = new File(firstLevelFolder);
        if (!firstLevelFolderFile.exists()) {
            firstLevelFolderFile.mkdir();
        }
        //读取文本文件
        List<String> txtList = new ArrayList<>();
        StringBuffer buffer = new StringBuffer();
        InputStream inputstream = new FileInputStream(new File(txtFile));
        BufferedReader reader = null;
        String temp = "";
        try {
            reader = new BufferedReader(new InputStreamReader(inputstream));
            while ((temp = reader.readLine()) != null) {
                if (!StringUtil.isBlank(temp.trim())) {
                    if (temp.trim().contains("*********")) {
                        txtList.add(buffer.toString());
                        buffer = new StringBuffer();
                    } else {
                        buffer.append(temp.trim());
                        buffer.append("\n");
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputstream != null) {
                try {
                    inputstream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //对文件批量处理
        String[] punctuation = {"。", "、", "；", "：", "？", "！", "•", ".", "，", "\n"};
        List<String> punctuations = Arrays.asList(punctuation);
        for (String str : txtList) {
            String folderName = "";
            String filename = str.substring(str.length() - 10, str.length());
            for (char name : filename.toCharArray()) {
                String nameStr = name + "";
                if (!punctuations.contains(nameStr)) {
                    if (folderName.length() > 3) {
                        break;
                    }
                    folderName = folderName + name;
                }
            }
            File newFolder = new File(firstLevelFolder + File.separator + folderName);
            if (!newFolder.exists()) {
                newFolder.mkdir();
            }
            //复制背景音乐
            copyFile(sourceFile.get(0).getAbsolutePath(), newFolder.getAbsolutePath());
            int randomNumber = 0 + (int) (Math.random() * (mp4list.size() + 1));
            //复制背景视频
            File videoFile = mp4list.get(randomNumber);
            copyFile(videoFile.getAbsolutePath(), newFolder.getAbsolutePath());
            //写入文件
            FileWriter writer = null;
            try {
                String finalpath = newFolder.getAbsolutePath() + File.separator + folderName + ".txt";
                writer = new FileWriter(finalpath, false);
                writer.write(str);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                if (writer != null) {
                    writer.flush();
                    writer.close();
                }
            }
        }
    }

    private void copyFile(String sourceFile, String desfolder) {
        // 源文件路径
        Path source = Paths.get(sourceFile);
        // 目标文件夹路径
        Path destinationDir = Paths.get(desfolder);
        // 目标文件路径
        Path destination = destinationDir.resolve(source.getFileName());
        try {
            // 确保目标文件夹存在
            Files.createDirectories(destinationDir);
            // 使用Files.copy()方法复制文件到目标文件夹
            Files.copy(source, destination);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
